import React, { useState, useEffect } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Checkbox } from '@/components/ui/checkbox'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { 
  Download, 
  FileText, 
  FolderOpen, 
  FolderTree, 
  Building2,
  CheckCircle,
  XCircle,
  Pause,
  Play,
  AlertCircle,
  FileDown,
  Archive
} from 'lucide-react'
import { ExportManager } from '@/lib/export-manager'
import { ExportFormat, ExportType, ExportSession, ExportProgress, MergeOption } from '@/lib/export-types'
import { message } from '@/lib/message'

interface ExportModalProps {
  isOpen: boolean
  onClose: () => void
  exportType: ExportType
  teamId?: string
  projectId?: string
  directoryId?: string
  docId?: string
  projectName: string
  directoryName?: string
  docTitle?: string
}

export default function ExportModal({
  isOpen,
  onClose,
  exportType,
  teamId,
  projectId,
  directoryId,
  docId,
  projectName,
  directoryName,
  docTitle
}: ExportModalProps) {
  const [format, setFormat] = useState<ExportFormat>(ExportFormat.MARKDOWN)
  const [mergeOption, setMergeOption] = useState<MergeOption>(MergeOption.SEPARATE)
  const [addWatermark, setAddWatermark] = useState(false)
  const [isExporting, setIsExporting] = useState(false)
  const [currentSession, setCurrentSession] = useState<ExportSession | null>(null)
  const [progress, setProgress] = useState<ExportProgress | null>(null)
  const [error, setError] = useState<string | null>(null)

  const exportManager = ExportManager.getInstance()

  // 跟踪format状态变化
  useEffect(() => {
    console.log('ExportModal format 状态变化:', format)
  }, [format])

  // 获取导出类型描述
  const getExportTypeDescription = () => {
    switch (exportType) {
      case ExportType.SINGLE:
        if (docId && docId.includes(',')) {
          const docCount = docId.split(',').length
          return `导出多个文档：${docCount} 个文档`
        }
        return `导出文档：${docTitle || '未命名文档'}`
      case ExportType.DIRECTORY:
        return `导出目录及子目录：${directoryName || '未命名目录'}`
      case ExportType.CURRENT_DIRECTORY:
        return `导出当前目录：${directoryName || '未命名目录'}`
      case ExportType.PROJECT:
        return `导出整个项目：${projectName}`
      default:
        return '导出文档'
    }
  }

  // 获取格式描述
  const getFormatDescription = (format: ExportFormat) => {
    const isMultiDoc = exportType === ExportType.DIRECTORY || 
                      exportType === ExportType.CURRENT_DIRECTORY || 
                      exportType === ExportType.PROJECT ||
                      (exportType === ExportType.SINGLE && docId && docId.includes(','))
    const mergeDesc = isMultiDoc && mergeOption === MergeOption.MERGE ? '（合并为单个文件）' : ''
    const separateDesc = isMultiDoc && mergeOption === MergeOption.SEPARATE ? '（分别导出文件，打包为ZIP）' : ''
    
    switch (format) {
      case ExportFormat.MARKDOWN:
        return `Markdown格式，适合技术文档${mergeDesc}${separateDesc}`
      case ExportFormat.HTML:
        return `HTML格式，适合网页查看${mergeDesc}${separateDesc}`
      case ExportFormat.PDF:
        return `PDF格式，适合打印和分享${mergeDesc}${separateDesc}`
      default:
        return ''
    }
  }

  // 获取格式图标
  const getFormatIcon = (format: ExportFormat) => {
    switch (format) {
      case ExportFormat.MARKDOWN:
        return <FileText className="w-4 h-4" />
      case ExportFormat.HTML:
        return <FileText className="w-4 h-4" />
      case ExportFormat.PDF:
        return <FileText className="w-4 h-4" />
      default:
        return <FileText className="w-4 h-4" />
    }
  }

  // 获取导出类型图标
  const getExportTypeIcon = () => {
    switch (exportType) {
      case ExportType.SINGLE:
        return <FileText className="w-5 h-5" />
      case ExportType.DIRECTORY:
        return <FolderTree className="w-5 h-5" />
      case ExportType.CURRENT_DIRECTORY:
        return <FolderOpen className="w-5 h-5" />
      case ExportType.PROJECT:
        return <Building2 className="w-5 h-5" />
      default:
        return <FileText className="w-5 h-5" />
    }
  }

  // 获取合并选项描述
  const getMergeOptionDescription = (option: MergeOption) => {
    const isMultiDoc = exportType === ExportType.DIRECTORY || 
                      exportType === ExportType.CURRENT_DIRECTORY || 
                      exportType === ExportType.PROJECT ||
                      (exportType === ExportType.SINGLE && docId && docId.includes(','))
    
    if (!isMultiDoc) {
      return option === MergeOption.MERGE ? '合并为单个文件' : '分别导出文件'
    }
    
    switch (option) {
      case MergeOption.MERGE:
        return '合并为单个文件，所有文档内容整合到一个文件中'
      case MergeOption.SEPARATE:
        return '分别导出文件，每个文档单独导出，最终打包为ZIP文件'
      default:
        return ''
    }
  }

  // 获取合并选项图标
  const getMergeOptionIcon = (option: MergeOption) => {
    switch (option) {
      case MergeOption.MERGE:
        return <FileDown className="w-4 h-4" />
      case MergeOption.SEPARATE:
        return <Archive className="w-4 h-4" />
      default:
        return <FileText className="w-4 h-4" />
    }
  }

  // 开始导出
  const handleExport = async () => {
    if (!teamId || !projectId) {
      setError('缺少必要的参数')
      return
    }

    console.log('ExportModal handleExport 被调用:', {
      exportType,
      format,
      mergeOption,
      teamId,
      projectId,
      directoryId,
      docId,
      addWatermark,
      projectName,
      directoryName,
      docTitle
    })

    setIsExporting(true)
    setError(null)

    try {
      // 创建导出会话
      const session = exportManager.createSession(
        exportType,
        format,
        {
          teamId,
          projectId,
          directoryId,
          docId,
          mergeOption,
          addWatermark
        }
      )

      console.log('创建的导出会话:', session)

      setCurrentSession(session)

      // 执行导出
      await exportManager.executeExport(
        session,
        projectName,
        directoryName,
        (progress) => {
          setProgress(progress)
        }
      )

      message.success('导出成功')
      onClose()

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '导出失败'
      setError(errorMessage)
      message.error(errorMessage)
    } finally {
      setIsExporting(false)
      setCurrentSession(null)
      setProgress(null)
    }
  }

  // 取消导出
  const handleCancel = () => {
    if (currentSession) {
      exportManager.cancelSession(currentSession.sessionId)
    }
    setIsExporting(false)
    setCurrentSession(null)
    setProgress(null)
    setError(null)
  }

  // 重置状态
  useEffect(() => {
    if (!isOpen) {
      setIsExporting(false)
      setCurrentSession(null)
      setProgress(null)
      setError(null)
    }
  }, [isOpen])

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {getExportTypeIcon()}
            导出文档
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* 导出信息 */}
          <div className="space-y-2">
            <Label className="text-sm font-medium">导出内容</Label>
            <div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg">
              {getExportTypeIcon()}
              <span className="text-sm text-gray-700">{getExportTypeDescription()}</span>
            </div>
          </div>

          {/* 导出格式 */}
          <div className="space-y-3">
            <Label className="text-sm font-medium">导出格式</Label>
            <RadioGroup value={format} onValueChange={(value) => {
              console.log('RadioGroup onValueChange 被调用:', { value, type: typeof value })
              setFormat(value as ExportFormat)
            }}>
              {Object.values(ExportFormat).map((formatOption) => (
                <div key={formatOption} className="flex items-center space-x-2">
                  <RadioGroupItem value={formatOption} id={formatOption} />
                  <Label htmlFor={formatOption} className="flex items-center gap-2 cursor-pointer">
                    {getFormatIcon(formatOption)}
                    <span className="capitalize">{formatOption}</span>
                    <span className="text-xs text-gray-500">
                      {getFormatDescription(formatOption)}
                    </span>
                  </Label>
                </div>
              ))}
            </RadioGroup>
          </div>

          {/* 合并选项 - 在多文档导出或单文档多选时显示 */}
          {(exportType === ExportType.DIRECTORY || 
            exportType === ExportType.CURRENT_DIRECTORY || 
            exportType === ExportType.PROJECT ||
            (exportType === ExportType.SINGLE && docId && docId.includes(','))) && (
            <div className="space-y-3">
              <Label className="text-sm font-medium">合并选项</Label>
              <RadioGroup value={mergeOption} onValueChange={(value) => {
                console.log('RadioGroup onValueChange 被调用:', { value, type: typeof value })
                setMergeOption(value as MergeOption)
              }}>
                {Object.values(MergeOption).map((option) => (
                  <div key={option} className="flex items-center space-x-2">
                    <RadioGroupItem value={option} id={option} />
                    <Label htmlFor={option} className="flex items-center gap-2 cursor-pointer">
                      {getMergeOptionIcon(option)}
                      <span className="capitalize">{getMergeOptionDescription(option)}</span>
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            </div>
          )}

          {/* 水印选项 */}
          <div className="flex items-center space-x-2">
            <Checkbox
              id="watermark"
              checked={addWatermark}
              onCheckedChange={(checked) => setAddWatermark(checked as boolean)}
            />
            <Label htmlFor="watermark" className="text-sm cursor-pointer">
              添加 "free-doc" 水印
            </Label>
          </div>

          {/* 导出进度 */}
          {isExporting && progress && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium">导出进度</Label>
                <Badge variant={progress.status === 'completed' ? 'default' : 'secondary'}>
                  {progress.current}/{progress.total}
                </Badge>
              </div>
              <Progress value={(progress.current / progress.total) * 100} />
              <div className="flex items-center gap-2 text-sm text-gray-600">
                {progress.status === 'completed' && <CheckCircle className="w-4 h-4 text-green-500" />}
                {progress.status === 'error' && <XCircle className="w-4 h-4 text-red-500" />}
                {progress.status === 'paused' && <Pause className="w-4 h-4 text-yellow-500" />}
                {(progress.status === 'preparing' || progress.status === 'downloading' || progress.status === 'processing') && <Play className="w-4 h-4 text-blue-500" />}
                <span>{progress.message}</span>
              </div>
            </div>
          )}

          {/* 错误信息 */}
          {error && (
            <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg">
              <AlertCircle className="w-4 h-4 text-red-500" />
              <span className="text-sm text-red-700">{error}</span>
            </div>
          )}

          {/* 操作按钮 */}
          <div className="flex justify-end gap-2">
            <Button
              variant="outline"
              onClick={isExporting ? handleCancel : onClose}
              disabled={isExporting}
            >
              {isExporting ? '取消' : '关闭'}
            </Button>
            <Button
              onClick={handleExport}
              disabled={isExporting || !teamId || !projectId}
              className="flex items-center gap-2"
            >
              <Download className="w-4 h-4" />
              {isExporting ? '导出中...' : '开始导出'}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
} 